package export

import (
	"encoding/csv"
	"fmt"
	"game/game-design/loader"
	"io"
	"os"
)

type CsvIO struct {
}

// 读取csv文件
func (c *CsvIO) Read(fileFullName string, designDefine *loader.DesignDefine) ([]*loader.DesignFile, error) {
	var designFiles []*loader.DesignFile = make([]*loader.DesignFile, 0)
	file0, err := os.Open(fileFullName)
	if err != nil {
		fmt.Println(err)
		return designFiles, err
	}
	reader := csv.NewReader(file0)

	rows := make([][]string, 0)
	var unfinish bool = true
	for unfinish {
		oneRow, err := reader.Read()
		if err != nil && err == io.EOF {
			unfinish = false
			break
		}
		rows = append(rows, oneRow)
	}

	fileInfo, err := os.Stat(fileFullName)
	if err != nil {
		return designFiles, err
	}

	dFile, err := loader.NewDesignFile(fileInfo.Name(), rows, designDefine)
	if err == nil {
		designFiles = append(designFiles, dFile)
	}
	return designFiles, nil
}

// 写csv文件
func (c *CsvIO) Write(designFile *loader.DesignFile, outputPath string, expectType string) {
	os.Mkdir(outputPath, 0755)
	if !designFile.FileNeedExport(expectType) {
		fmt.Println(expectType, "导出忽略\t", designFile.Name)
		return
	}

	file, err := os.OpenFile(fmt.Sprintf("%s%s.csv", outputPath, designFile.GetOutputName()), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
	if err != nil {
		fmt.Println(expectType, "导出异常\t", designFile.Name)
		return
	}
	defer file.Close()

	writer := csv.NewWriter(file)

	marcos := make([]string, 0)
	marcos = append(marcos, designFile.Macros...)
	writer.Write(marcos)

	names := make([]string, 0, len(designFile.Fields))
	forms := make([]string, 0, len(designFile.Fields))
	tags := make([]string, 0, len(designFile.Fields))
	comments := make([]string, 0, len(designFile.Fields))

	for _, field := range designFile.Fields {
		needExport := designFile.FieldNeedExport(field.Tag(), expectType)
		if !needExport {
			continue
		}
		names = append(names, field.Name())
		forms = append(forms, field.Form())
		tags = append(tags, field.Tag())
		comments = append(comments, field.Comment())
	}

	fieldLines := make([][]string, 4)
	fieldLines[designFile.DesignDefine.NameOffset-1] = names
	fieldLines[designFile.DesignDefine.TypeOffset-1] = forms
	fieldLines[designFile.DesignDefine.TagOffset-1] = tags
	fieldLines[designFile.DesignDefine.CommentOffset-1] = comments

	for _, line := range fieldLines {
		writer.Write(line)
	}

	for _, data := range designFile.Datas {
		var rowDatas []string
		for i, field := range designFile.Fields {
			needExport := designFile.FieldNeedExport(field.Tag(), expectType)
			if !needExport {
				continue
			}
			if i >= len(data) {
				rowDatas = append(rowDatas, "")
			} else {
				rowDatas = append(rowDatas, data[i])
			}
		}
		writer.Write(rowDatas)
	}
	writer.Flush()
	fmt.Println("导出成功", designFile.Name)
}
